function onTab(tab) {
  let tabItem = document.getElementsByClassName('tabBar-item')
  if(!tab) {
    tabItem[1].style.backgroundColor = 'unset'
    document.getElementsByClassName('intro')[0].style.display = 'block'
    document.getElementsByClassName('step-info')[0].style.display = 'none'
  }else {
    tabItem[0].style.backgroundColor = 'unset'
    document.getElementsByClassName('step-info')[0].style.display = 'block'
    document.getElementsByClassName('intro')[0].style.display = 'none'
  }
  tabItem[tab].style.backgroundColor = '#FF6200'
}

function onFold() {
  // let classVal = document.getElementById("icon-unfold");
  if(!unfold) {
    document.getElementsByClassName('left')[0].style.width = '0'
    document.getElementsByClassName('unfold')[0].style.left = '40px'
    document.getElementsByClassName('right')[0].style.width = '100vw'
    document.getElementsByClassName('unfold-arrow')[0].innerHTML = "》"
    // classVal.classList.remove('layui-icon-left')
    // classVal.classList.add('layui-icon-right')
    // classVal.style.marginLeft = '7px'
  }else {
    document.getElementsByClassName('left')[0].style.width = '25vw'
    document.getElementsByClassName('unfold')[0].style.left = 'calc(25vw + 40px)'
    document.getElementsByClassName('right')[0].style.width = 'calc(75vw - 66px)'
    document.getElementsByClassName('unfold-arrow')[0].innerHTML = "《"
    // classVal.classList.remove('layui-icon-right')
    // classVal.classList.add('layui-icon-left')
    // classVal.style.marginLeft = '0'
  }
  unfold = !unfold;
}

function startLoading(index) {
  loading = true
  layer.close(index)
  element.progress('demo', '50%')
}

function endLoading() {
  element.progress('demo', '100%')
  loading = false
  window.setTimeout(function () {
    element.progress('demo', '0%')
  }, 3000)
}

function reload() {
  location.href = location.href + "#login-vm"
}

function logger(msg) {
  let n = document.getElementById("logger");
  if (n) {
    let p = n.innerHTML;
    n.innerHTML = p + "<p>" + msg + "</p>"
    console.log(msg)
  }
}

function autoGoVnc() {
  logger("goVNC")
  try {
    if (window.app || typeof app != "undefined") {
      logger("go app.login")
      try {
        app.login(id, pwd)
      } catch (e) {
        logger(e.toString())
      }
    } else {
      let vnc_display = document.getElementById('vnc_container');
      vnc_display.src = novnc_url;
      /*if (vnc_display.attachEvent) {
        // IE
        vnc_display.attachEvent('onload', function() {
          console.log('iframe加载完毕！')
          setVNC()
        })
      } else { // 非IE
        vnc_display.onload = function() {
            console.log('iframe加载完毕！')
            setVNC()
          }
      }*/
    }
  }catch (e) {
    logger(e.toString())
  }
  return
}

function toggleFullScreen() {
  let text = document.getElementById("full-screen-text");
  if (document.fullscreenElement) {
    isFullScreen = false
    text.innerHTML = "全屏"
    // 退出全屏
    document.exitFullscreen()
      .then(() => {
        //console.log('退出全屏成功');
        unfold = true
        onFold()
        document.getElementsByClassName('left')[0].style.width = '25vw'
        document.getElementsByClassName('unfold')[0].style.left = 'calc(25vw + 40px)'
        document.getElementsByClassName('right')[0].style.width = 'calc(75vw - 66px)'
        document.getElementsByClassName('header')[0].style.display = 'flex'
        document.getElementsByClassName('content')[0].style.height = 'calc(100% - 55px)'
      })
      .catch((error) => {
          console.error('退出全屏失败', error);
      });
  } else {
    isFullScreen = true
    text.innerHTML = "退出全屏"
    // 进入全屏
    document.documentElement.requestFullscreen()
      .then(() => {
        //console.log('进入全屏成功');
        document.getElementsByClassName('left')[0].style.width = '0'
        document.getElementsByClassName('unfold')[0].style.left = '40px'
        document.getElementsByClassName('right')[0].style.width = '100%'
        document.getElementsByClassName('header')[0].style.display = 'none'
        document.getElementsByClassName('content')[0].style.height = '100%'
      })
      .catch((error) => {
          console.error('进入全屏失败', error);
      });
  }
}

function toggleStepList() {
  if(!isStepList) {
    isStepList = true
    document.getElementsByClassName('step-list')[0].style.display = 'block'
  }else {
    isStepList = false
    document.getElementsByClassName('step-list')[0].style.display = 'none'
  }
}

function changeList(index, arr = describeList, startData = insId) {
  isStepList = false
  document.getElementsByClassName('step-list')[0].style.display = 'none'
  // if(!arr)arr = describeList
  // list item style
  if(arr.length) {
    arr.forEach((item, key) => {
      if(key == index) {
        document.getElementsByClassName('step-item')[index].style.color = "var(--main-color)"
        document.getElementsByClassName('step-item')[index].style.backgroundColor = "#665347"
        document.getElementsByClassName('step-header-title')[0].innerHTML = arr[index].title
        document.getElementsByClassName('step-detail')[0].innerHTML = arr[index].detail
      }else {
        document.getElementsByClassName('step-item')[key].style.color = "white"
        document.getElementsByClassName('step-item')[key].style.backgroundColor = "unset"
      }
    })
  }
  // pre, next btn
  let preBtn = document.getElementById('pre-btn')
  let nextBtn = document.getElementById('next-btn')
  if(index == 0 && arr.length != 1) {
    preBtn.classList.add('info-btn')
    nextBtn.classList.add('main-btn')
    preBtn.classList.remove('main-btn')
    nextBtn.classList.remove('info-btn')
    nextBtn.setAttribute('onclick', `changeList(${index + 1}, ${JSON.stringify(arr)}, '${startData}')`)
    nextBtn.innerHTML = '下一步'
  }else if(index == 0 && arr.length == 1) {
    nextBtn.classList.add('main-btn')
    preBtn.classList.remove('info-btn')
    preBtn.innerHTML = ""
    nextBtn.classList.remove('info-btn')
    if(instanceData.Status != "UNCREATED") {
      nextBtn.setAttribute('onclick', `openComplete()`)
    }
    nextBtn.innerHTML = '完成'
  }else if(index == (arr.length - 1)) {
    preBtn.classList.add('main-btn')
    nextBtn.classList.add('main-btn')
    preBtn.classList.remove('info-btn')
    nextBtn.classList.remove('info-btn')
    preBtn.setAttribute('onclick', `changeList(${index - 1}, ${JSON.stringify(arr)}, '${startData}')`)
    if(instanceData.Status != "UNCREATED") {
      nextBtn.setAttribute('onclick', `openComplete()`)
    }
    nextBtn.innerHTML = '完成'
  }else {
    preBtn.classList.add('main-btn')
    nextBtn.classList.add('main-btn')
    preBtn.classList.remove('info-btn')
    nextBtn.classList.remove('info-btn')
    preBtn.setAttribute('onclick', `changeList(${index - 1}, ${JSON.stringify(arr)}, '${startData}')`)
    nextBtn.setAttribute('onclick', `changeList(${index + 1}, ${JSON.stringify(arr)}, '${startData}')`)
    nextBtn.innerHTML = '下一步'
  }
}

function onDrawerTab(tab) {
  let tabItem = document.getElementsByClassName('drawer-tabItem')
  if(!tab) {
    tabItem[1].style.color = 'white'
    tabItem[1].style.borderBottom = '2px #333333 solid'
    document.getElementsByClassName('drawer-export')[0].style.display = 'none'
    document.getElementsByClassName('drawer-upload')[0].style.display = 'block'
    document.getElementsByClassName('drawer-footer-0')[0].style.display = 'flex'
    document.getElementsByClassName('drawer-footer-1')[0].style.display = 'none'
  }else {
    tabItem[0].style.color = 'white'
    tabItem[0].style.borderBottom = '2px #333333 solid'
    document.getElementsByClassName('drawer-upload')[0].style.display = 'none'
    document.getElementsByClassName('drawer-export')[0].style.display = 'block'
    document.getElementsByClassName('drawer-footer-0')[0].style.display = 'none'
    document.getElementsByClassName('drawer-footer-1')[0].style.display = 'block'
  }
  tabItem[tab].style.color = '#FF6200'
  tabItem[tab].style.borderBottom = '2px #FF6200 solid'
}

function toggleDrawerFile(ip) {
  if(!drawerShow) {
    getDownloadFiles(ip)
    document.getElementsByClassName('drawer-file ')[0].style.width = '550px'
  }else {
    document.getElementsByClassName('drawer-file ')[0].style.width = '0'
  }
  drawerShow = !drawerShow;
}

function calVMDisk(ip) {
  fetch(`/ttp/api/stu/experiment/df-h/?ip=${ip}&port=7079`).then(response => {
    if (!response.ok) {
      throw new Error('网络请求失败');
    }
    return response.json(); // 解析响应为 JSON 数据
  }).then(res => {
    // 在这里处理获取的数据
    // console.log('~disk', res);
    if(res.data.total) {
      document.getElementById("free-disk").innerHTML = res.data.total.free + 'GB'
      document.getElementById("total-disk").innerHTML = res.data.total.total + 'GB'
    }
  })
  .catch(error => {
    // 处理请求失败
    console.error(error);
  });
}

function netLink(ip) {
  isNetTesting = true
  fetch(`http://${ip}:7079/test-internet-speed`).then(response => {
    if (!response.ok) {
      throw new Error('网络请求失败');
    }
    return response.json(); // 解析响应为 JSON 数据
  }).then(res => {
    // 在这里处理获取的数据
    // console.log('~net linking', res);
    if(res.data) {
      document.getElementById("net-btn").style.display = "block"
      if(res.data.download_speed <= 350) {
        document.getElementById("net-btn").style.color = "#FF0000"
        document.getElementById("net-btn").style.backgroundColor = "white"
        document.getElementById("net-btn").innerHTML = "网络繁忙"
      }else {
        document.getElementById("net-btn").style.color = "#33FF81"
        document.getElementById("net-btn").style.backgroundColor = "#4C4C4C"
        document.getElementById("net-btn").innerHTML = "网络正常"
        document.getElementById("download-text").style.display = "block"
        document.getElementById("download-text").innerHTML = `网络下载速度为${res.data.download_speed}`
        document.getElementById("upload-text").style.display = "block"
        document.getElementById("upload-text").innerHTML = `网络上传速度为${res.data.upload_speed}`
        document.getElementById("net-speed-testing").innerHTML = "检测完成"
      }
    }else {
      document.getElementById("net-dialog").style.display = "none"
      alert("网速测试出问题了，请关闭等会儿再试试~")
    }
    isNetTesting = false
  })
  .catch(error => {
    // 处理请求失败
    console.error(error);
    isNetTesting = false
  });
}

function getDownloadFiles(ip) {
  models.vmTransFileModel.fileList({ip}, function(res) {
    //console.log('~download files', res)
    canTransFile = true
    let arr = res.data.file_transfer_station_files

    let optionsContainer = document.getElementById('files-options');
    while (optionsContainer.firstChild) {
      optionsContainer.removeChild(optionsContainer.firstChild);
    }

    // 渲染动态选项
    arr.forEach(function(item) {
      let box = document.createElement('div');
      box.style.marginBottom = '10px'
      let checkbox = document.createElement('input');
      checkbox.style.marginRight = '15px'
      checkbox.type = 'checkbox';
      checkbox.name = 'files-option';
      checkbox.value = item;
      box.appendChild(checkbox);

      let label = document.createElement('label');
      label.textContent = item;
      box.appendChild(label);

      optionsContainer.appendChild(box);
      
      // 添加事件监听器，监听选择
      checkbox.addEventListener('change', function(e) {
        //console.log('~~~e', e.target.value)
        let selectValue = e.target.value
        /*
        if (checkbox.checked) {
            console.log('download-files选择了：' + item.value);
        }
        */
        if(!selectedFiles.includes(selectValue)) {
          selectedFiles.push(selectValue)
        }else {
          let idx = selectedFiles.indexOf(selectValue)
          selectedFiles.splice(idx, 1)
        }
        //console.log('~~~selectedFiles', selectedFiles)
      });
    });
    let transDom = document.getElementById("can-trans-files");
    transDom.style.display = "block"
  }, function(err) {
    console.log('~download files failed', err)
  })
}

function downFiles(ip) {
  if(selectedFiles.length == 0) {
    alert('没有选择到要下载的文件。');
    return
  }
  // 假设服务器返回的响应是blob对象
  fetch(`http://${ip}:7079/file-download?fileName=` + (selectedFiles.length > 1 ? selectedFiles.join(',') : selectedFiles[0]))
    .then(response => response.blob())
    .then(blob => {
      // 创建一个blob URL并生成下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = selectedFiles.length > 1 ? 'data.zip' : selectedFiles[0]; // 设置下载的文件名和扩展名
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      //下载完成
      selectedFiles = []
      toggleDrawerFile(ip)
      alert('文件下载成功！');
    })
    .catch(error => {
      console.error('下载出错：', error);
    });
}

  function getCookie(name) {
  const cookieValue = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
  return cookieValue ? cookieValue[2] : null;
}

function onUpload(ip) {
  // 获取文件输入框和上传按钮
  let fileInput = document.getElementById('fileInput');
  let uploadButton = document.getElementById('uploadButton');

  // 添加点击事件监听器
  uploadButton.addEventListener('click', function() {
    // 触发文件选择对话框
    fileInput.click();
  });

  // 文件选择事件监听器
  fileInput.addEventListener('change', function() {
      const selectedFile = fileInput.files[0];
      const maxSizeInBytes = 100 * 1024 * 1024; // 100MB
      if (selectedFile.size > maxSizeInBytes) {
        alert('上传文件已超过100MB，请重新选择文件')
        return
      }
      console.log('~~~file', fileInput.files[0])
      if (selectedFile) {
          // 创建一个 FormData 对象
          let formData = new FormData();

          // 将文件添加到 FormData，参数名为 "file"
          formData.append('file', selectedFile);

          // 执行上传操作（你需要将这里的URL替换为实际的上传地址）
          // let uploadUrl = `http://${ip}:7079/file-upload`; // 替换为实际的上传URL
          let uploadUrl = `/ttp/api/stu/experiment/file-upload/${ip}`; // 替换为实际的上传URL
          let xhr = new XMLHttpRequest();
          // 获取 CSRF 令牌的值
          const csrfToken = getCookie('csrftoken');
          console.log("experiment.js")
         console.log(csrfToken)
         xhr.open('POST', uploadUrl, true);
         xhr.setRequestHeader('X-CSRFToken',csrfToken)
         xhr.send(formData);
          xhr.onreadystatechange = function() {
              if (xhr.readyState === 4 && xhr.status === 200) {
                  toggleDrawerFile(ip)
                  alert('文件上传成功！');
              } else if (xhr.status !== 200) {
                  alert('文件上传失败！');
              }
          };
      } else {
          alert('没有选择到文件或出问题了。');
      }
  });
}